package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author atguigu-mqx
 * @ClassName TrackStrategy
 * @description: TODO
 * @date 2025年04月26日
 * @version: 1.0
 */
@Service("1002")
public class TrackStrategy implements ItemTypeStrategy {

    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        //  购买声音 user_paid_track
        //  10,11,12,13,14,15
        //  要购买的声音Id 列表；
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();
        //  根据声音Id获取声音对象;
        Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(itemIdList.get(0));
        Assert.notNull(trackInfoResult, "查询声音信息失败！");
        TrackInfo trackInfo = trackInfoResult.getData();
        Assert.notNull(trackInfo, "查询声音信息失败！");
        //  查询用户已购买的声音Id;
        //  List<Long> userPaidTrackIdList = findUserPaidTrackList(trackInfo.getAlbumId(), userPaidRecordVo.getUserId());
        List<Long> userPaidTrackIdList = userPaidTrackMapper.selectList(new LambdaQueryWrapper<UserPaidTrack>().eq(UserPaidTrack::getUserId, userPaidRecordVo.getUserId()).eq(UserPaidTrack::getAlbumId, userPaidRecordVo.getItemIdList().get(0))).stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
        //  循环遍历;
        for (Long trackId : itemIdList) {
            //  判断！
            if (!CollectionUtils.isEmpty(userPaidTrackIdList)) {
                //  获取相同的数据;发送消息退款;
                if (userPaidTrackIdList.contains(trackId)) {
                    //  发送消息退款； 封装一个实体类; trackId; userId; amount; 调用wx支付api 或 增加账户余额;
                    //  rabbitService.sendDealyMessage(MqConst.EXCHANGE_ORDER_CANCEL, MqConst.ROUTING_ORDER_CANCEL, trackId);
                }
            }
            //  查询的是空！
            //  创建对象；
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            userPaidTrack.setUserId(userPaidRecordVo.getUserId());
            userPaidTrack.setAlbumId(trackInfo.getAlbumId());
            userPaidTrack.setTrackId(trackId);
            userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidTrackMapper.insert(userPaidTrack);
        }
    }
}
